#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <windows.h>

const double PI = 3.1416;
const double DELTA = 15.0;
const int MAX_BLOCK_SIZE = 32;
const int MIN_BLOCK_SIZE = 4;
const int IMAGE_SIZE = 128;
const int SEARCH_RANGE = 2;

double ***AnSeries, ****SourceImageCode, ****TargetImageCode;
double **SourceImage, **TargetImage;
int **TargetImageMap;

typedef struct{ /* bmfh */ 
	unsigned char bfType[2];
	unsigned char bfSize[4];
	unsigned char bfReserved1[2]; 
	unsigned char bfReserved2[2];
	unsigned char bfOffBits[4];
} BMP_BITMAPFILEHEADER;    

typedef struct { /* bmi */ 
	BITMAPINFOHEADER bmiHeader;
	RGBQUAD bmiColors[1];
} BMP_BITMAPINFO; 

typedef struct{ /* bmih */ 
	DWORD biSize; 
	LONG biWidth; 
	LONG biHeight; 
	WORD biPlanes; 
	WORD biBitCount; 
	DWORD biCompression; 
	DWORD biSizeImage; 
	LONG biXPelsPerMeter; 
	LONG biYPelsPerMeter; 
	DWORD biClrUsed; 
	DWORD biClrImportant;
} BMP_BITMAPINFOHEADER; 

typedef struct{/*ImageBlock*/
	int Row;
	int Column;
	int Dimension;
} ImageBlock;

typedef struct{
	int k;	int l; //SourceImage Block
	int x;  int y; //SourceImage pixies
	int r;	int s; //TargetImage Block
	int u;	int v; //TargetImage pixies
	int BlockSize; // o
	double z0;
	double p0;
	double distance0;
	int d[3];
	double z[3][3];
	double p[3][3];
	double distance[3];
	int IsSimilar;
	double ** Delta;
} CheckResult;

typedef struct {/*CheckBlock*/
	int BlockSize; 
	double z0;
	double p0;
	double distance0;
	int IsSimilar;
} SimCheckResult ;

//*************************************************************************************

int loadMYBMP(char *file, int tag){
    BMP_BITMAPFILEHEADER filehead;
    BMP_BITMAPINFOHEADER bmi;
    FILE *fp;
	unsigned char Temp;
	int i,j,flag=0;
	int BytesPerLine;
	long OffBits;

	if (tag==0){
		SourceImage = (double **)malloc(sizeof(double*)*IMAGE_SIZE);
		for (i=0;i<IMAGE_SIZE;i++){
			SourceImage[i]= (double *)malloc(sizeof(double)*IMAGE_SIZE);
			for(j=0;j<IMAGE_SIZE;j++){
				SourceImage[i][j]=1.0;
			}
		}	
	}
	else{
		TargetImage = (double **)malloc(sizeof(double*)*IMAGE_SIZE);
		for (i=0;i<IMAGE_SIZE;i++){
			TargetImage[i]= (double *)malloc(sizeof(double)*IMAGE_SIZE);
			for(j=0;j<IMAGE_SIZE;j++){
				TargetImage[i][j]=i*IMAGE_SIZE+(j+1.0);
			}
		}
	}
    
	fp=fopen(file,"rb"); 
    if (fp!=NULL){
        fseek(fp,0,0);
        fread(&filehead,sizeof(filehead),1,fp);
        fread(&bmi,sizeof(bmi),1,fp);
		OffBits = 1078;
		if (bmi.biCompression==0){
			flag=1;
			BytesPerLine=(((bmi.biWidth*bmi.biBitCount+7)/8)+3)/4*4;
			fseek(fp,OffBits,0);
			for(i=0;i<bmi.biHeight;i++){
				for(j=0;j<bmi.biWidth;j++){
					fread(&Temp,1,1,fp);
					if (tag==0){
						SourceImage[i][j] = (double)Temp;
					}
					else{
						TargetImage[i][j] = (double)Temp;
					}
				}
			}
			fclose(fp); 
		}
	}
    return flag;
}
